<?php

namespace app\home\controller;

//引入公共控制器
use app\common\Controller\Home;

// 引入邮箱发送类
use app\common\library\Email;

//系统配置的模型
use app\common\model\Config as ConfigModel;

class Business extends Home
{
    public $NoLogin = ['centernot'];

    protected $RegionModel = null;
    protected $EMSModel = null;
    protected $SubjectModel = null;
    protected $OrderModel = null;
    protected $CategoryModel = null;
    protected $CommentModel = null;
    protected $RecordModel = null;
    protected $ReceiveModel = null;

    public function __construct()
    {
        //继承父类的构造函数
        parent::__construct();

        //加载模型
        // $this->BusinessModel = model('Business.Business');
        $this->RegionModel = model('Region');
        $this->EMSModel = model('Ems');
        $this->SubjectModel = model('Subject.Subject');
        $this->OrderModel = model('Subject.Order');
        $this->CategoryModel = model('Subject.Category');
        $this->CommentModel = model('Subject.Comment');
        $this->RecordModel = model('Business.Record');
        $this->ReceiveModel = model('Coupon.Receive');
    }

    public function centernot()
    {
        return $this->view->fetch();
    }

    //个人中心
    public function center()
    {
        return $this->view->fetch();
    }

    // 基本资料
    public function profile()
    {
        if ($this->request->isPost()) {
            //接收所有数据
            // $parmas = $this->request->param();
            // var_dump($parmas);
            // exit;

            //接收数据
            $nickname = $this->request->param('nickname', '', 'trim');
            $mobile = $this->request->param('mobile', '', 'trim');
            $email = $this->request->param('email', '', 'trim');
            $password = $this->request->param('password', '', 'trim');
            $gender = $this->request->param('gender', '', 'trim');
            $region = $this->request->param('region', '', 'trim');

            //组装数据
            $data = [
                'id' => $this->view->AutoLogin['id'], //要有ID才会更新
                'mobile' => $mobile,
                'nickname' => $nickname,
                'gender' => $gender,
            ];

            //判断密码是否不为空
            if (!empty($password)) {
                //新的密码盐
                $salt = randstr(10);

                //对密码进行加密
                $repass = md5($password . $salt);

                //追加新数据
                $data['password'] = $repass;
                $data['salt'] = $salt;
            }

            //判断邮箱是否为新邮箱，如果是新邮箱需要重新验证
            if ($email != $this->view->AutoLogin['email']) {
                $data['email'] = $email;
                $data['auth'] = '0';
            }

            //查询当前所在区域
            if ($region) {
                $parent = $this->RegionModel->where(['code' => $region])->value('parentpath');

                if ($parent) {
                    $parent = explode(',', $parent);

                    $province = isset($parent[0]) ? $parent[0] : null;
                    $city = isset($parent[1]) ? $parent[1] : null;
                    $district = isset($parent[2]) ? $parent[2] : null;

                    $data['province'] = $province;
                    $data['city'] = $city;
                    $data['district'] = $district;
                }
            }

            //判断是否有文件上传
            if ($_FILES['avatar']['error'] == 0 && $_FILES['avatar']['size'] > 0) {
                //上传头像的方法
                $success = build_upload('avatar');

                if ($success['code']) {
                    //把新的图片存放下来
                    $data['avatar'] = $success['data'];
                } else {
                    $this->error($success['msg']);
                    exit;
                }
            }

            //准备更新数据库
            $result = $this->BusinessModel->validate('common/Business/Business')->isUpdate(true)->save($data);

            if ($result === FALSE) {
                $this->error($this->BusinessModel->getError());
                exit;
            } else {
                //如果他之前是有旧头像 要删除掉旧的头像
                // 判断是否有上传图片
                if (isset($data['avatar'])) {
                    //判断文件是否存在，如果存在就删除掉
                    @is_file("." . $this->view->AutoLogin['avatar']) && @unlink("." . $this->view->AutoLogin['avatar']);
                }

                $this->success('更新个人资料成功', url('home/business/center'));
                exit;
            }
        }

        return $this->view->fetch();
    }

    // 我的订单
    public function order()
    {
        if ($this->request->isAjax()) {
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');

            //偏移量
            $start = ($page - 1) * $limit;

            $where = ['order.busid' => $this->view->AutoLogin['id']];

            //查询数据总条数
            $count = $this->OrderModel->with(['subject', 'comment'])->where($where)->count();

            //查询数据
            $list = $this->OrderModel
                ->with(['subject', 'comment'])
                ->where($where)
                ->limit($start, $limit)
                ->select();

            if ($list) {
                foreach ($list as $item) {
                    $cateid = isset($item['subject']['cateid']) ? trim($item['subject']['cateid']) : 0;

                    $item['cate'] = $this->CategoryModel->where(['id' => $cateid])->value('name');
                }
            }

            $data = [
                'count' => $count,
                'list' => $list
            ];

            if ($list) {
                //成功返回
                $this->success('返回列表', null, $data);
                exit;
            } else {
                //失败返回
                $this->error('暂无数据', null, $data);
                exit;
            }
        }

        return $this->view->fetch();
    }
    // 评价界面
    public function comment()
    {
        $orderid = $this->request->param('orderid', 0, 'trim');

        $order = $this->OrderModel->with(['subject', 'comment'])->find($orderid);

        if (!$order) {
            $this->error('订单不存在');
            exit;
        }

        if ($this->request->isPost()) {
            $rate = $this->request->param('rate', 5, 'trim');
            $content = $this->request->param('content', '', 'trim');

            $data = [
                'busid' => $this->view->AutoLogin['id'],
                'subid' => $order['subid'],
                'rate' => $rate,
                'content' => $content,
                'orderid' => $order['id']
            ];

            $result = $this->CommentModel->validate('common/Subject/Comment')->save($data);

            if ($result === FALSE) {
                $this->error($this->CommentModel->getError());
                exit;
            } else {
                $this->success('评价成功', url('home/business/order'));
                exit;
            }
        }

        $this->assign('order', $order);

        return $this->view->fetch();
    }

    // 我的课程
    public function course()
    {
        $where = ['order.busid' => $this->view->AutoLogin['id']];

        //查询数据
        $list = $this->OrderModel
            ->with(['subject'])
            ->where($where)
            ->select();

        $subject = $this->SubjectModel->with(['category', 'teacher'])->select();

        $this->assign([
            'list' => $list,
            'subject' => $subject,
        ]);

        return $this->view->fetch();
    }

    // 我的优惠券
    public function coupon_list()
    {
        $list = $this->ReceiveModel->with(['coupon'])->where(['busid' => $this->view->AutoLogin['id']])->select();

        $this->assign('list', $list);

        return $this->view->fetch();
    }

    // 我的收藏
    public function collection()
    {

        $id = $this->view->AutoLogin['id'];

        $subject = $this->SubjectModel->with('category', 'teacher')->where("find_in_set($id,collects)")->select();

        $this->assign('subject', $subject);

        return $this->view->fetch();
    }

    // 邮箱认证
    public function email()
    {

        //拦截判断
        if ($this->view->AutoLogin['auth'] == '1') {
            $this->error('您已经通过邮箱认证，无需重复认证', url('home/business/center'));
            exit;
        }

        // 判断是否有ajax请求过来
        if ($this->request->isAjax()) {
            // 接收action参数
            $action = $this->request->param('action', '', 'trim');

            // 发送验证码
            if ($action == "send") {
                // 接收对方邮箱
                $receive = $this->view->AutoLogin['email'];

                // 实例化邮件对象
                $email = new Email;

                // 生成随机字符串
                $code = randstr(5);
                $subject = "【FAST邮箱验证】";
                $message = "<h3>您的邮箱验证码为：$code</h3>";

                // 删除掉邮箱之前的所有的验证码
                // 开启事务
                $this->EMSModel->startTrans();

                // 执行删除语句
                $DeleteStatus = $this->EMSModel->where(['email' => $receive])->delete();

                if ($DeleteStatus === FALSE) {
                    $this->error('过期验证码删除失败!');
                    exit;
                }

                // 组装要插入的数据
                $data = [
                    'event' => 'auth', //自己命名的事件名称
                    'email' => $receive, //收件人
                    'code' => $code, //生成随机字符串
                    'times' => 0, //验证次数
                ];

                // 插入语句
                $InsertStatus = $this->EMSModel->save($data);

                // 插入失败
                if ($InsertStatus === FALSE) {
                    //回滚上一步的动作
                    $this->EMSModel->rollback();
                    $this->error('插入验证码失败');
                    exit;
                }

                // 综合的判断
                if ($DeleteStatus === FALSE || $InsertStatus === FALSE) {
                    $this->EMSModel->rollback();
                    $this->error('存入验证码失败');
                    exit;
                }

                // 发送验证码
                $result = $email->to($receive)
                    ->subject($subject)
                    ->message($message)
                    ->send();

                if ($result) {
                    // 提交事务
                    $this->EMSModel->commit();

                    // 发送邮件成功了
                    $this->success('邮件已发送，请注意查收');
                    exit;
                } else {
                    // 如果邮件发送失败了，那么数据库要回滚回去
                    $this->EMSModel->rollback();
                    $this->error("邮件发送失败：" . $email->getError());
                    exit;
                }

                var_dump($receive);
                exit;
            }
        }

        // 用于接收表单的判断
        if ($this->request->isPost()) {
            $email = $this->view->AutoLogin['email'];

            // 接收验证码
            $code = $this->request->param('code', '', 'trim');

            // 先查看验证码是否正确
            $where = [
                'email' => $email,
                'code' => $code
            ];

            $check = $this->EMSModel->where($where)->find();

            if (!$check) {
                $this->error('验证码输入有误，请重新输入');
                exit;
            }

            // 开启事务
            $this->EMSModel->startTrans();
            $this->BusinessModel->startTrans();

            // 删除邮件记录表
            $EMStatus = $this->EMSModel->where($where)->delete();

            // 打印语句
            // echo $this->EMSModel->getLastSql();
            // exit;

            if ($EMStatus === FALSE) {
                $this->error('验证码删除失败');
                exit;
            }

            // 会员表的更新
            $data = [
                'id' => $this->view->AutoLogin['id'],
                'auth' => '1',      # 已认证
            ];

            // 执行更新语句
            $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($data);

            // 打印语句
            // echo $this->BusinessModel->getLastSql();
            // exit;

            if ($BusinessStatus === FALSE) {
                // 邮件回滚
                $this->EMSModel->rollback();
                $this->error($this->BusinessModel->getError());
                exit;
            }

            // 综合判断
            if ($EMStatus === FALSE || $BusinessStatus === FALSE) {
                $this->BusinessModel->rollback();
                $this->EMSModel->rollback();
                $this->error('验证状态更新失败');
                exit;
            } else {
                // 提交事务
                $this->EMSModel->commit();
                $this->BusinessModel->commit();
                $this->success('邮箱认证成功', url('home/business/center'));
                exit;
            }
        }

        return $this->view->fetch();
    }

    // 消费记录
    public function record()
    {
        $record = $this->RecordModel->select();

        $this->assign('record', $record);

        return $this->view->fetch();
    }

    // 余额充值
    public function recharge()
    {
        $mony = $this->BusinessModel->where(['id' => $this->view->AutoLogin['id']])->find();

        $this->assign('mony', $mony);

        if ($this->request->isPost()) {
            //接收数据
            $nickname = $this->request->param('nickname', '', 'trim');
            $moneyold = $this->request->param('moneyold', '', 'trim');
            $moneynew = $this->request->param('moneynew', '', 'trim');

            $money = ($moneyold + $moneynew);


            //组装数据
            $data = [
                'id' => $this->view->AutoLogin['id'], //要有ID才会更新
                'mobile' => $this->view->AutoLogin['mobile'],
                'nickname' => $nickname,
                'money' => $money
            ];

            //准备更新数据库
            $result = $this->BusinessModel->validate('common/Business/Business')->isUpdate(true)->save($data);

            if ($result === FALSE) {
                $this->error($this->BusinessModel->getError());
                exit;
            } else {
                $this->success('余额充值成功', url('home/business/recharge'));
                exit;
            }
        }

        return $this->view->fetch();
    }

    // 联系我们
    public function contact()
    {
        return $this->view->fetch();
    }
}
